﻿using ClinicSystem.configure;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace ClinicSystem.FormPage
{
	public partial class WndDrugInfo : Form
	{
		List<string> drugNames = new List<string>();
		List<string> inventory_play = new List<string>();
		List<string> price_play = new List<string>();
		List<string> maker_play = new List<string>();
		List<string> creator_play = new List<string>();
		List<string> changer_play = new List<string>();

		DataTable dt = new DataTable();
		public WndDrugInfo()
		{
			InitializeComponent();
		}

		private void initDataList()
		{

			drugNames = Load_OutFile.CmdQuery("SELECT name FROM drugInformation");
			inventory_play = Load_OutFile.CmdQuery("SELECT inventory FROM drugInformation");
			price_play = Load_OutFile.CmdQuery("SELECT price FROM drugInformation");
			maker_play = Load_OutFile.CmdQuery("SELECT maker FROM drugInformation");
			creator_play = Load_OutFile.CmdQuery("SELECT creator FROM drugInformation");
			changer_play = Load_OutFile.CmdQuery("SELECT changer FROM drugInformation");

			dt.Columns.Add("名称", typeof(string));
			dt.Columns.Add("库存(克)", typeof(float));
			dt.Columns.Add("单价(克/元)", typeof(float));
			dt.Columns.Add("制造厂商", typeof(string));
			dt.Columns.Add("创建人", typeof(string));
			dt.Columns.Add("修改人", typeof(string));


			for (int i = 0; i < drugNames.Count; i++)
			{
				dt.Rows.Add(drugNames[i], inventory_play[i], price_play[i], maker_play[i], creator_play[i], changer_play[i]);
			}
			dataGridView_drug.Columns.Clear();
			dataGridView_drug.DataSource = dt;
			dataGridView_drug.Columns[1].Width = 120;
			dataGridView_drug.Columns[2].Width = 180;
			dataGridView_drug.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;


		}

		private void WndDrugInfo_Load(object sender, EventArgs e)
		{
			initDataList();
		}

		private void updataList()
		{
			drugNames = Load_OutFile.CmdQuery("SELECT name FROM drugInformation");
			inventory_play = Load_OutFile.CmdQuery("SELECT inventory FROM drugInformation");
			price_play = Load_OutFile.CmdQuery("SELECT price FROM drugInformation");
			maker_play = Load_OutFile.CmdQuery("SELECT maker FROM drugInformation");
			creator_play = Load_OutFile.CmdQuery("SELECT creator FROM drugInformation");
			changer_play = Load_OutFile.CmdQuery("SELECT changer FROM drugInformation");


			dt.Clear();
			for (int i = 0; i < drugNames.Count; i++)
			{
				dt.Rows.Add(drugNames[i], inventory_play[i], price_play[i], maker_play[i], creator_play[i], changer_play[i]);
			}
		}
		private void button_refresh_Click(object sender, EventArgs e)
		{
			drugNames = Load_OutFile.CmdQuery("SELECT name FROM drugInformation");
			inventory_play = Load_OutFile.CmdQuery("SELECT inventory FROM drugInformation");
			price_play = Load_OutFile.CmdQuery("SELECT price FROM drugInformation");
			maker_play = Load_OutFile.CmdQuery("SELECT maker FROM drugInformation");
			creator_play = Load_OutFile.CmdQuery("SELECT creator FROM drugInformation");
			changer_play = Load_OutFile.CmdQuery("SELECT changer FROM drugInformation");

			dt.Rows.Clear();
			for (int i = 0; i < drugNames.Count; i++)
			{
				dt.Rows.Add(drugNames[i], inventory_play[i], price_play[i], maker_play[i], creator_play[i], changer_play[i]);
			}
		}

		private void button_add_Click(object sender, EventArgs e)
		{
			string addName = "'"+textBox_name.Text+"'";
			string addWright = textBox_weight.Text;
			string addPrice = textBox_price.Text;
			string addMaker = "'"+textBox_maker.Text+"'";
			List<string> name=new List<string>() { "name","inventory","price","maker","creator","changer"};
			List<string> value = new List<string>() { addName, addWright, addPrice,addMaker, "'"+GlobalVar.currentUser+"'", "'"+GlobalVar.currentUser+"'" };
			Load_OutFile.InsertData("drugInformation", name, value);
			updataList();
		}

		internal List<List<string>> drugTable= new List<List<string>>();
		private void linkLabel_csvAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			using (OpenFileDialog opendialog=new OpenFileDialog())
			{
				opendialog.Filter = "CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*";
				opendialog.Title = "选择CSV文件";
				if(opendialog.ShowDialog()==DialogResult.OK)
				{
					try
					{
						string filePath=opendialog.FileName;
						using (StreamReader sr=new StreamReader(filePath))
						{
							string line;
							while((line=sr.ReadLine())!=null)
							{
								string[] afterLine = line.Split(',');
								drugTable.Add(new List<string>(afterLine));
							}
						}
						if (drugTable[0][0] == "名称" && drugTable[0][1] == "重量(克)" && drugTable[0][2] == "单价(元/克)" && drugTable[0][3] == "制造厂商")
						{
							List<string> name=new List<string>() { "name", "inventory", "price", "maker","creator","changer" };
							List<string> value=new List<string>();
							for (int row = 1; row < drugTable.Count; row++)
							{
								for (int col = 0; col < drugTable[row].Count; col++)
								{
									if(col==0||col==3)
									{
										value.Add("'"+drugTable[row][col]+"'");
									}else
									value.Add(drugTable[row][col]);
								}
								value.Add("'"+GlobalVar.currentUser+"'");
								value.Add("'"+GlobalVar.currentUser+"'");
								Load_OutFile.InsertData("drugInformation", name, value);
								value.Clear();
							}
						}else
						{
							label_Info.Text = "文件列名错误，请使用模板";
						}
					}
					catch(Exception ex)
					{
						label_Info.Text = ex.Message;
					}
				}
			}
		}
		private void linkLabel_csv_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			using (SaveFileDialog saveDialog = new SaveFileDialog())
			{
				saveDialog.Title = "保存CSV文件";
				saveDialog.Filter = "CSV文件 (*.csv)|*.csv"; // 文件类型过滤器
				saveDialog.FileName = "药品信息.csv"; // 默认文件名
				saveDialog.AddExtension = true; // 自动添加扩展名
				saveDialog.RestoreDirectory = true; // 记忆上次目录

				if (saveDialog.ShowDialog() == DialogResult.OK)
				{
					string filePath = saveDialog.FileName;
					systemCsv(filePath); // 生成CSV文件
					linkLabel_csv.LinkVisited = true; // 标记链接已访问（可选）
					MessageBox.Show("文件保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
			}
		}

		private void systemCsv(string filePath)
		{
			List<string[]> colHead=new List<string[]> { new[] { "名称","重量(克)","单价(元/克)","制造厂商"} };
			StringBuilder csvContent = new StringBuilder();
			foreach (var row in colHead)
			{
				csvContent.AppendLine(string.Join(",", row.Select(field =>
					field.Contains(",") ? $"\"{field}\"" : field
				)));
			}
			File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);
		}

		private void textBox_name_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == (char)8 || e.KeyChar == (char)127) return; // 退格和删除键放行

			// 拦截数字字符（0-9）
			if (Char.IsDigit(e.KeyChar))
			{
				e.Handled = true; // 阻止输入
				label_Info.Text = "禁止输入数字！";
			}
		}

		private void textBox_weight_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (char.IsControl(e.KeyChar))
			{
				return;
			}

			// 允许数字
			if (char.IsDigit(e.KeyChar))
			{
				return;
			}

			// 允许小数点（但只能有一个）
			if (e.KeyChar == '.' || e.KeyChar == ',')
			{
				// 统一处理为小数点
				e.KeyChar = '.'; // 强制转换为小数点

				// 检查是否已存在小数点
				if (this.Text.Contains('.'))
				{
					e.Handled = true; // 阻止输入
				}
				return;
			}


				e.Handled = true; // 阻止输入
				label_Info.Text = "输入数字！";

		}

		private void dataGridView_drug_SelectionChanged(object sender, EventArgs e)
		{
			button_cancel.Enabled=dataGridView_drug.SelectedRows.Count > 0;
		}

		private void button_cancel_Click(object sender, EventArgs e)
		{
			if (dataGridView_drug.SelectedRows.Count == 0) return;
			if(MessageBox.Show($"确定要删除选中的 {dataGridView_drug.SelectedRows.Count} 行吗？",
					   "确认删除",
					   MessageBoxButtons.YesNo,
					   MessageBoxIcon.Warning) != DialogResult.Yes)
			{
				return;
			}
			var deleteRow = dataGridView_drug.SelectedRows.Cast<DataGridViewRow>().ToList();
			foreach(DataGridViewRow row in deleteRow)
			{
				string name= "'"+row.Cells[0].Value.ToString()+"'";
				string inventory = "'" + row.Cells[1].Value.ToString()+"'";
				Load_OutFile.CmdDelete("DELETE FROM drugInformation WHERE name = "+name+" AND inventory = "+inventory);
				
			}
			updataList();
		}
	}
}
